import { useEffect, useMemo, useState } from 'react';
import { useRequest, useSetState } from 'ahooks';
import { pick, omit } from 'lodash';
import moment from 'moment';
import { fetchOptionList, fetchTree } from '@/services/marketingMap';
import { flattenToCodeNameMap, transformData, getPath } from '@/utils/marketingMap/utils';
import { message } from 'antd';

const useForm = (auth: boolean, isLoading = true, isDate = true) => {
  const { data, loading } = useRequest(() => Promise.all([fetchOptionList(), fetchTree()]));
  const [initialValue, setInitialValue] = useState<any>({});

  const [query, setQuery] = useSetState(initialValue);

  const { options, codeNameMaps } = useMemo(
    () => ({
      options: transformData(data?.[0] || []),
      codeNameMaps: flattenToCodeNameMap(data?.[0] || []),
    }),
    [data?.[0]],
  );

  const codeNameMap = useMemo(
    () => ({
      region: codeNameMaps[query.region],
      subregion: codeNameMaps[query.subregion],
      city: codeNameMaps[query.city],
      store: codeNameMaps[query.store],
    }),
    [codeNameMaps, query],
  );

  const handleSubmit = (_query: typeof initialValue) => {
    window.sessionStorage.setItem('marketingMapQuery', JSON.stringify({ ...query, ..._query }));
    setQuery(_query);
  };

  useEffect(() => {
    setQuery(initialValue);
  }, [initialValue]);

  useEffect(() => {
    if (data && !isLoading) {
      const terr = data?.[1]?.[0];

      if (window.sessionStorage.getItem('marketingMapQuery')) {
        const marketingMapQuery = JSON.parse(
          window.sessionStorage.getItem('marketingMapQuery') || '{}',
        );
        setInitialValue(marketingMapQuery);
        return;
      }

      if (terr) {
        const paths = getPath(data?.[0], terr.orgCode);

        if (paths) {
          const [region, subregion, city, store] = paths;

          setInitialValue({
            region,
            subregion,
            city,
            store,
            areaRange: 5,
            brand: 'DFPV',
            timeRange: '1',
            summaryDate: moment().add(-2, 'd').format('YYYY-MM-DD'),
          });
        } else {
          if (auth) {
            setInitialValue({
              region: 'HZ',
              subregion: 'HBDQ_WH',
              city: '1801',
              store: 'HUB46',
              areaRange: 5,
              brand: 'DFPV',
              timeRange: '1',
              summaryDate: moment().add(-2, 'd').format('YYYY-MM-DD'),
            });
          } else {
            message.error('无数据权限，请联系管理员');
          }
        }
      }
    }
  }, [data, isLoading]);

  return {
    loading,
    options,
    // series: data?.[1],
    state: !Object.keys(query).length,
    query: isDate ? query : {...omit(query, ['timeRange']), summaryDate: moment().add(-2, 'd').format('YYYY-MM-DD')},
    initialValue,
    codeNameMap,
    onSubmit: handleSubmit,
    date: pick(query, ['summaryDate', 'timeRange']),
  };
};
 
export default useForm;
